package com.lunasoft.nettyprotobuf;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Jierry
 * @version 2016/7/13.
 */
public class SubReqClient {

    private SocketChannel socketChannel;

    public void connect(int port,String host)throws Exception{


        //配置客户端NIO线程组
        EventLoopGroup group = new NioEventLoopGroup();

        try{
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast(new ProtobufVarint32FrameDecoder())
                                    .addLast(new ProtobufDecoder(
                                            SubscribeRespProto.SubscribeResp.getDefaultInstance()))
                                    .addLast(new ProtobufVarint32LengthFieldPrepender())
                                    .addLast(new ProtobufEncoder())
                                    .addLast(new SubReqClientHandler());
                        };
                    });

            //发起异步连接操作
            ChannelFuture f = b.connect(host,port).sync();
            //等待客户端链路关闭
            //f.channel().closeFuture().sync();
            if (f.isSuccess()){
                socketChannel = (SocketChannel)f.channel();
                System.out.println("connect server  成功---------");
            }
        }finally{
            //退出，释放资源
            group.shutdownGracefully();
        }

    }

    public static void main(String[] args)throws Exception {
        int port = 12345;
        if(args!=null && args.length > 0){
            port = Integer.valueOf(args[0]);
        }
        SubReqClient client = new SubReqClient();
        client.connect(port, "127.0.0.1");
        //client.socketChannel.writeAndFlush(req(1));
        while (true){
            System.out.print("===========write message success=========="+"\r\n");
            client.socketChannel.writeAndFlush(req2(1));
            TimeUnit.SECONDS.sleep(5);
        }
    }

    private static LoginReqProto.LoginReq req(int i){
        LoginReqProto.LoginReq.Builder r = LoginReqProto.LoginReq.newBuilder();
        r.setLoginId(i);
        r.setUserName("leeka");
        return r.build();
    }

    private static SubscribeReqProto.SubscribeReq req2(int i){
        SubscribeReqProto.SubscribeReq.Builder r = SubscribeReqProto.SubscribeReq.newBuilder();
        r.setSubReqID(i);
        r.setProductName("Netty Book"+i);
        r.setUserName("leeka");

        List<String> address = new ArrayList<String>();
        address.add("Nanjing");
        r.addAllAddress(address);
        address.add("Beijing");
        return r.build();
    }
}
